package com.yeskery.nut.script.parser;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.util.IOUtils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;

/**
 * 基于文件的脚本元数据读取器
 * @author sprout
 * 2022-05-13 17:47
 */
public class FileScriptMetadataReader extends AbstractScriptMetadataReader {

    /** 脚本路径 */
    private final String scriptPath;

    /** 字符编码 */
    private Charset charset;

    /**
     * 构建文件的脚本元数据读取器
     * @param scriptMetadataParser 脚本元数据
     * @param scriptPath 脚本路径
     */
    public FileScriptMetadataReader(ScriptMetadataParser scriptMetadataParser, String scriptPath) {
        super(scriptMetadataParser);
        this.scriptPath = scriptPath;
    }

    /**
     * 构建文件的脚本元数据读取器
     * @param scriptMetadataParser 脚本元数据
     * @param charset 字符编码
     * @param scriptPath 脚本路径
     */
    public FileScriptMetadataReader(ScriptMetadataParser scriptMetadataParser, Charset charset, String scriptPath) {
        super(scriptMetadataParser);
        this.scriptPath = scriptPath;
        this.charset = charset;
    }

    @Override
    protected String getScriptResource() {
        try {
            return new String(IOUtils.readByteArray(new FileInputStream(scriptPath)), charset);
        } catch (FileNotFoundException e) {
            throw new NutException("Script File Not Found.", e);
        }
    }
}
